package com.zfp.sys.service;

import com.zfp.core.plugins.tree.TreeNode;
import com.zfp.core.service.BaseService;
import com.zfp.sys.dao.SysMenuDao;
import com.zfp.sys.dao.SysRoleDao;
import com.zfp.sys.entity.SysMenu;
import com.zfp.sys.entity.SysRole;
import com.zfp.sys.entity.SysUser;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Repository("sysRoleService")
public class SysRoleService extends BaseService<SysRole> {
	@Autowired
	private SysRoleDao sysRoleDao;
	@Autowired
	private SysMenuDao sysMenuDao;

	public String saveOrUpdate(SysRole sysRole, HttpSession session){
		SysUser sysUserSession = (SysUser) session.getAttribute("sessionUser");
		int row = 0;
		if(sysRole.getRoleId() == null){
			sysRole.setIsDeleted("n");
			sysRole.setCreatorId(Integer.parseInt(sysUserSession.getUserId().toString()));
			row = sysRoleDao.insert(sysRole);
		}else{
			row = sysRoleDao.update(sysRole);
		}
		return row >= 1?"success":"failure";
	}

	/**
	 * 得到该角色下的菜单树
	 * @param roleId
	 * @return 菜单表json类型的String
	 */
	public  String getMenuJsonTree(String roleId,SysUser sysUser) {
		//取到全部菜单
		SysMenu sysMenus =  new SysMenu();
		List<SysMenu> sysMenuList =  sysMenuDao.list("SysMenu.findAll", sysMenus);
		//取得该角色下的菜单ID
		List<SysMenu> sysRoleMenuList = sysMenuDao.list("SysMenu.findrolemenu",roleId);

		Map<String,String> menuIdMap = new HashMap<String,String>();
		for(SysMenu sysRoleMe:sysRoleMenuList){
			menuIdMap.put(sysRoleMe.getMenuId(), "");
		}
		JSONArray json = new JSONArray();
		for (SysMenu sysMenu : sysMenuList) {
			json.add(new TreeNode(sysMenu.getMenuId().toString(), sysMenu.getParentId().toString(), menuIdMap.containsKey(sysMenu.getMenuId()) ,sysMenu.getMenuName()));
		}
		return json.toString();
	}

	/**
	 * roleId角色下的菜单权限保存
	 * @param roleId  角色ID
	 * @param menuIds 菜单ID串
	 * @return
	 */
	public Boolean saveRoleMenuTr(String roleId,String menuIds){
		sysMenuDao.deleteById("SysMenu.deleteRoleMenu", Long.parseLong(roleId));
		if(menuIds!=null&&!"".equals(menuIds)){
			String[] menuIdArr = menuIds.split(",");
			for(String menuId : menuIdArr){
				SysMenu sysRoleMenu =  new SysMenu();
				sysRoleMenu.setMenuId(menuId);
				sysRoleMenu.setRoleId(roleId);
				sysMenuDao.insert("SysMenu.insertRoleMenu",sysRoleMenu);
			}
		}
		return true;
	}

}